/*
 * ViewMessages.java
 *
 * Created on Feb 20, 2011, 5:50:12 PM
 */
package edu.rit.varapp.graphical;

import edu.rit.varapp.datalayer.CustomerOps;
import edu.rit.varapp.datalayer.Message;
import edu.rit.varapp.datalayer.Post;
import edu.rit.varapp.utilities.ExceptionUtils;
import edu.rit.varapp.utilities.JTableUtils;
import java.awt.Dimension;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

/**
 *
 * @author Eric Kisner
 */
public class ViewMessages extends AbstractView {

    private final CustomerOps cOps = new CustomerOps();
    private final Post post = new Post();
    private static final int VIEW_WIDTH = 650;
    private static final int VIEW_HEIGHT = 400;
    private CustomerOperations parent;
    private int entityId;
    private int messageId;

    /** Creates new form ViewMessages */
    public ViewMessages( CustomerOperations parent, int entityId ) {
        super( new Dimension( VIEW_WIDTH, VIEW_HEIGHT ) );
        initComponents();
        this.parent = parent;
        this.entityId = entityId;
        initMessageTable();
    }

    private void setMessageId( int messageId ) {
        this.messageId = messageId;
    }

    private void refreshGUI() {
        messageTextArea.setText( "" );
        messageTableHolder.removeAll();
        initMessageTable();
    }

    private void initMessageTable() {
        try {
            ArrayList<Message> messages = post.retrieveMessages( entityId );
            String[] header = { "Date", "Subject", "Status" };
            JTable table = JTableUtils.getMessagesTable( header, messages, false );
            table = applyOptions( table );
            JScrollPane holder = new JScrollPane( table );
            messageTableHolder.add( holder );
            holder.setBounds( 0, 0, 550, 100 );
        } catch( SQLException sqle ) {
            ExceptionUtils.handleException( this, sqle, "There was an error trying to retrieve your messages."
                                                        + "\nPlease contact an administrator to view the log "
                                                        + "files for more information.", this.getClass() );
            return;
        }
    }

    /**
     * Apply any options to the dynamically created JTable.
     */
    private JTable applyOptions( final JTable table ) {
        final ArrayList<ArrayList<String>> data = JTableUtils.dataFromTable( table );
        table.setRowHeight( 30 );
        table.setRowMargin( 10 );
        table.setSelectionMode( javax.swing.ListSelectionModel.SINGLE_SELECTION );
        table.getSelectionModel().addListSelectionListener( new ListSelectionListener() {

            public void valueChanged( ListSelectionEvent lse ) {
                if( lse.getValueIsAdjusting() ) {
                    return;
                }
                //Since the table uses single_selection, there can only be one row selected at a time
                final int curRow = table.getSelectionModel().getLeadSelectionIndex();
                //Get the customer information of the current selected row
                ArrayList<String> messageData = data.get( curRow );
                try {
                    Message m = post.retrieveMessage( messageData.get( 0 ) );
                    post.updateMessageStatus( m );
                    setMessageId( m.getMessageId() );
                    messageTextArea.setText( m.getMessage() );
                } catch( SQLException sqle ) {
                    ExceptionUtils.handleException( ViewMessages.this, sqle,
                                                    "There was an error retrieving this message information."
                                                    + "\nPlease tell an administrator to check the log files "
                                                    + "for more details.", this.getClass() );
                    return;
                }
            }
        } );
        table.setShowHorizontalLines( false );
        table.setShowVerticalLines( false );
        return table;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings( "unchecked" )
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        messageTableHolder = new javax.swing.JPanel();
        actionsHolder = new javax.swing.JPanel();
        deleteMessageButton = new javax.swing.JButton();
        backButton = new javax.swing.JButton();
        messageDisplayHolder = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        messageTextArea = new javax.swing.JTextArea();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("View Messages");
        setMinimumSize(new java.awt.Dimension(650, 400));
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
        });
        getContentPane().setLayout(new java.awt.GridBagLayout());

        messageTableHolder.setLayout(null);
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.ipady = 100;
        gridBagConstraints.insets = new java.awt.Insets(20, 30, 20, 30);
        getContentPane().add(messageTableHolder, gridBagConstraints);

        actionsHolder.setLayout(new java.awt.GridLayout(1, 2, 30, 0));

        deleteMessageButton.setText("Delete Message");
        deleteMessageButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteMessageButtonActionPerformed(evt);
            }
        });
        actionsHolder.add(deleteMessageButton);

        backButton.setText("Back");
        backButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                backButtonActionPerformed(evt);
            }
        });
        actionsHolder.add(backButton);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.VERTICAL;
        gridBagConstraints.insets = new java.awt.Insets(20, 0, 20, 0);
        getContentPane().add(actionsHolder, gridBagConstraints);

        messageTextArea.setColumns(20);
        messageTextArea.setLineWrap(true);
        messageTextArea.setRows(5);
        messageTextArea.setWrapStyleWord(true);
        jScrollPane2.setViewportView(messageTextArea);

        javax.swing.GroupLayout messageDisplayHolderLayout = new javax.swing.GroupLayout(messageDisplayHolder);
        messageDisplayHolder.setLayout(messageDisplayHolderLayout);
        messageDisplayHolderLayout.setHorizontalGroup(
            messageDisplayHolderLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 574, Short.MAX_VALUE)
        );
        messageDisplayHolderLayout.setVerticalGroup(
            messageDisplayHolderLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 107, Short.MAX_VALUE)
        );

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.gridheight = 8;
        gridBagConstraints.fill = java.awt.GridBagConstraints.VERTICAL;
        gridBagConstraints.insets = new java.awt.Insets(21, 20, 21, 20);
        getContentPane().add(messageDisplayHolder, gridBagConstraints);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
        parent.setEnabled( true );
        parent.repaint();
        parent.validate();
        parent.toFront();   //Once we repaint the client view, we want to bring it to the front for convenience.
    }//GEN-LAST:event_formWindowClosed

    private void backButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_backButtonActionPerformed
        this.dispose();
    }//GEN-LAST:event_backButtonActionPerformed

    private void deleteMessageButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteMessageButtonActionPerformed
        try {
            if( messageId != -1 ) {
                post.deleteMessage( messageId );
                JOptionPane.showMessageDialog( this, "Successfully deleted the message." );
                refreshGUI();
            } else {
                JOptionPane.showMessageDialog( this, "You must select a message to delete first." );
                return;
            }
        } catch( SQLException sqle ) {
            ExceptionUtils.handleException( this, sqle, "There was an error deleting the message.\nPlease have an "
                                                        + "administrator check the log files for further information.",
                                            this.getClass() );
        }
    }//GEN-LAST:event_deleteMessageButtonActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel actionsHolder;
    private javax.swing.JButton backButton;
    private javax.swing.JButton deleteMessageButton;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JPanel messageDisplayHolder;
    private javax.swing.JPanel messageTableHolder;
    private javax.swing.JTextArea messageTextArea;
    // End of variables declaration//GEN-END:variables
}
